package netty.http.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by zhj on 15-10-21.
 */
public class HttpClient {

    public void connect(String host, int port,URI uri) throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // 客户端接收到的是httpResponse响应，所以要使用HttpResponseDecoder进行解码
                    ch.pipeline().addLast(new HttpResponseDecoder());
                    // 客户端发送的是httprequest，所以要使用HttpRequestEncoder进行编码
                    ch.pipeline().addLast(new HttpRequestEncoder());
                    ch.pipeline().addLast(new HttpClientInboundHandler());
                }
            });

            // Start the client.
            ChannelFuture f = b.connect(host, port).sync();


            String msg = "Are you ok?";
            DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                    uri.toASCIIString()/*, *//*Unpooled.wrappedBuffer(new byte[10*1024])*//*null*/);

            // 构建http请求
            request.headers().set(HttpHeaders.Names.HOST, host);
            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
//            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
            // 发送http请求
            f.channel().write(request);
            f.channel().flush();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
//        test1();
        ///download.oracle.com/otn-pub/java/jdk/8u65-b17/jdk-8u65-solaris-x64.tar.gz?AuthParam=1445925300_6589abf14332f5dd1607f65c0042cca1
        test2();
    }
    //测试下大文件的下载
    private static void test2() throws Exception {
        HttpClient client = new HttpClient();
        URI uri = new URI("http://down.bigbaicai.com/20150715/Install_DBC_v7_3.exe");
        client.connect("down.bigbaicai.com", 80,uri);
    }

    private static void test1() throws Exception {
        HttpClient client = new HttpClient();
        URI uri = new URI("http://127.0.0.1:8080");
        client.connect("127.0.0.1", 8080,uri);
    }
}
